package service

import (
	"errors"
	"gorm.io/gorm/clause"
	"wit-admin-go/system/app/dto"
	"wit-admin-go/system/app/model"
	"wit-admin-go/system/utils"
)

type roleService struct{}

var RoleService = new(roleService)

// PostCreateRole  创建角色
func (us *roleService) PostCreateRole(role dto.Role) (err error) {
	return utils.DB.Create(&role).Error
}

// PutUpdateRole 修改角色
func (us *roleService) PutUpdateRole(role dto.Role) (err error) {
	_, errN := us.GetRoleById(role.Id)
	if errN != nil {
		return errN
	}
	roles := new(model.Role)
	return utils.DB.Model(&roles).Where("id = ?", role.Id).Updates(role).Error
}

// PutUpdateRoleMenu 角色添加菜单
func (us *roleService) PutUpdateRoleMenu(roleId string, menuId []string) (err error) {
	role, errN := us.GetRoleById(roleId)
	if errN != nil {
		return errN
	}
	menu := new([]model.Menu)
	utils.DB.Where("id IN ?", menuId).Find(&menu)
	return utils.DB.Model(&role).Association("Menu").Replace(menu)
}

// GetRoleById 通过ID查询数据
func (us *roleService) GetRoleById(id string) (role *model.Role, err error) {
	err = utils.DB.Preload("Menu").First(&role, "id = ?", id).Error
	menu := utils.GetTree("", role.Menu)
	role.Menu = menu
	if err != nil {
		return role, errors.New("数据没找到")
	}
	return role, err
}

// GetRoleList 获取所有数据
func (us *roleService) GetRoleList(page *dto.RolePage) (*[]model.Role, int64) {
	role := new([]model.Role)
	db := utils.DB.Preload(clause.Associations)
	if page.Name != "" {
		db = db.Where("name LIKE ?", "%"+page.Name+"%")
	}
	total := db.Scopes(utils.Paginate(page.PageNum, page.PageSize)).Find(&role).RowsAffected
	if total > 0 {
		return role, total
	} else {
		return nil, 0
	}
}

// DelRole 删除数据
func (us *roleService) DelRole(id string, userId string) (err error) {
	role, errN := us.GetRoleById(id)
	if errN != nil {
		return errN
	}
	role.DeleteId = userId
	err = utils.DB.Delete(&role, "id = ?", id).Error
	return err
}

// RemoveRole 永久删除数据
func (us *roleService) RemoveRole(id string) (err error) {
	role := new(model.Role)
	err = utils.DB.Unscoped().Delete(&role, "id = ?", id).Error
	return err
}
